/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pt.iasd.youthshelter.datacore.controller;

import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import pt.iasd.youthshelter.datamodel.Pathfinder;
import pt.iasd.youthshelter.datamodel.Lider;
import pt.iasd.youthshelter.datamodel.ProgressiveClass;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Tuple;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import org.openide.util.lookup.ServiceProvider;
import pt.iasd.youthshelter.datacore.EntityManagerSemaphore;
import pt.iasd.youthshelter.datacore.controller.exceptions.NonexistentEntityException;
import pt.iasd.youthshelter.datamodel.Honor;
import pt.iasd.youthshelter.datamodel.Club;
import pt.iasd.youthshelter.datamodel.Investiture;
import pt.iasd.youthshelter.datamodel.service.InvestitureController;

/**
 *
 * @author Rui
 */
@ServiceProvider(service=InvestitureController.class)
public class InvestitureJpaController implements Serializable, InvestitureController {

    private EntityManager aquireEntityManager() throws InterruptedException {
        EntityManagerSemaphore.getInstance().getSemaphore().acquire();
        return EntityManagerSemaphore.getInstance().getEntityManager();
    }
    
    private void releaseEntityManager(EntityManager em) {
        if (em != null && em.isOpen()) {
            em.close();
        }
        EntityManagerSemaphore.getInstance().getSemaphore().release();
    }

    @Override
    public void create(Investiture investiture) {
        if (investiture.getProgressiveClassList() == null) {
            investiture.setProgressiveClassList(new ArrayList<ProgressiveClass>());
        }
        if (investiture.getHonorList() == null) {
            investiture.setHonorList(new ArrayList<Honor>());
        }
        if (investiture.getClubList() == null) {
            investiture.setClubList(new ArrayList<Club>());
        }
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Pathfinder pathfinderId = investiture.getPathfinderId();
            if (pathfinderId != null) {
                pathfinderId = em.getReference(pathfinderId.getClass(), pathfinderId.getId());
                investiture.setPathfinderId(pathfinderId);
            }
            Lider liderId = investiture.getLiderId();
            if (liderId != null) {
                liderId = em.getReference(liderId.getClass(), liderId.getId());
                investiture.setLiderId(liderId);
            }
            List<ProgressiveClass> attachedProgressiveClassList = new ArrayList<ProgressiveClass>();
            for (ProgressiveClass progressiveClassListProgressiveClassToAttach : investiture.getProgressiveClassList()) {
                progressiveClassListProgressiveClassToAttach = em.getReference(progressiveClassListProgressiveClassToAttach.getClass(), progressiveClassListProgressiveClassToAttach.getId());
                attachedProgressiveClassList.add(progressiveClassListProgressiveClassToAttach);
            }
            investiture.setProgressiveClassList(attachedProgressiveClassList);
            List<Honor> attachedHonorList = new ArrayList<Honor>();
            for (Honor honorListHonorToAttach : investiture.getHonorList()) {
                honorListHonorToAttach = em.getReference(honorListHonorToAttach.getClass(), honorListHonorToAttach.getId());
                attachedHonorList.add(honorListHonorToAttach);
            }
            investiture.setHonorList(attachedHonorList);
            List<Club> attachedClubList = new ArrayList<Club>();
            for (Club clubListClubToAttach : investiture.getClubList()) {
                clubListClubToAttach = em.getReference(clubListClubToAttach.getClass(), clubListClubToAttach.getId());
                attachedClubList.add(clubListClubToAttach);
            }
            investiture.setClubList(attachedClubList);
            em.persist(investiture);
            if (pathfinderId != null) {
                pathfinderId.getInvestitureList().add(investiture);
                em.merge(pathfinderId);
            }
            if (liderId != null) {
                liderId.getInvestitureList().add(investiture);
                em.merge(liderId);
            }
            for (ProgressiveClass progressiveClassListProgressiveClass : investiture.getProgressiveClassList()) {
                progressiveClassListProgressiveClass.getInvestitureList().add(investiture);
                progressiveClassListProgressiveClass = em.merge(progressiveClassListProgressiveClass);
            }
            for (Honor honorListHonor : investiture.getHonorList()) {
                honorListHonor.getInvestitureList().add(investiture);
                honorListHonor = em.merge(honorListHonor);
            }
            for (Club clubListClub : investiture.getClubList()) {
                clubListClub.getInvestitureList().add(investiture);
                clubListClub = em.merge(clubListClub);
            }
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void edit(Investiture investiture) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Investiture persistentInvestiture = em.find(Investiture.class, investiture.getId());
            Pathfinder pathfinderIdOld = persistentInvestiture.getPathfinderId();
            Pathfinder pathfinderIdNew = investiture.getPathfinderId();
            Lider liderIdOld = persistentInvestiture.getLiderId();
            Lider liderIdNew = investiture.getLiderId();
            List<ProgressiveClass> progressiveClassListOld = persistentInvestiture.getProgressiveClassList();
            List<ProgressiveClass> progressiveClassListNew = investiture.getProgressiveClassList();
            List<Honor> honorListOld = persistentInvestiture.getHonorList();
            List<Honor> honorListNew = investiture.getHonorList();
            List<Club> clubListOld = persistentInvestiture.getClubList();
            List<Club> clubListNew = investiture.getClubList();
            if (pathfinderIdNew != null) {
                pathfinderIdNew = em.getReference(pathfinderIdNew.getClass(), pathfinderIdNew.getId());
                investiture.setPathfinderId(pathfinderIdNew);
            }
            if (liderIdNew != null) {
                liderIdNew = em.getReference(liderIdNew.getClass(), liderIdNew.getId());
                investiture.setLiderId(liderIdNew);
            }
            List<ProgressiveClass> attachedProgressiveClassListNew = new ArrayList<ProgressiveClass>();
            for (ProgressiveClass progressiveClassListNewProgressiveClassToAttach : progressiveClassListNew) {
                progressiveClassListNewProgressiveClassToAttach = em.getReference(progressiveClassListNewProgressiveClassToAttach.getClass(), progressiveClassListNewProgressiveClassToAttach.getId());
                attachedProgressiveClassListNew.add(progressiveClassListNewProgressiveClassToAttach);
            }
            progressiveClassListNew = attachedProgressiveClassListNew;
            investiture.setProgressiveClassList(progressiveClassListNew);
            List<Honor> attachedHonorListNew = new ArrayList<Honor>();
            for (Honor honorListNewHonorToAttach : honorListNew) {
                honorListNewHonorToAttach = em.getReference(honorListNewHonorToAttach.getClass(), honorListNewHonorToAttach.getId());
                attachedHonorListNew.add(honorListNewHonorToAttach);
            }
            honorListNew = attachedHonorListNew;
            investiture.setHonorList(honorListNew);
            List<Club> attachedClubListNew = new ArrayList<Club>();
            for (Club clubListNewClubToAttach : clubListNew) {
                clubListNewClubToAttach = em.getReference(clubListNewClubToAttach.getClass(), clubListNewClubToAttach.getId());
                attachedClubListNew.add(clubListNewClubToAttach);
            }
            clubListNew = attachedClubListNew;
            investiture.setClubList(clubListNew);
            investiture = em.merge(investiture);
            if (pathfinderIdOld != null && !pathfinderIdOld.equals(pathfinderIdNew)) {
                pathfinderIdOld.getInvestitureList().remove(investiture);
                pathfinderIdOld = em.merge(pathfinderIdOld);
            }
            if (pathfinderIdNew != null && !pathfinderIdNew.equals(pathfinderIdOld)) {
                pathfinderIdNew.getInvestitureList().add(investiture);
                em.merge(pathfinderIdNew);
            }
            if (liderIdOld != null && !liderIdOld.equals(liderIdNew)) {
                liderIdOld.getInvestitureList().remove(investiture);
                liderIdOld = em.merge(liderIdOld);
            }
            if (liderIdNew != null && !liderIdNew.equals(liderIdOld)) {
                liderIdNew.getInvestitureList().add(investiture);
                em.merge(liderIdNew);
            }
            for (ProgressiveClass progressiveClassListOldProgressiveClass : progressiveClassListOld) {
                if (!progressiveClassListNew.contains(progressiveClassListOldProgressiveClass)) {
                    progressiveClassListOldProgressiveClass.getInvestitureList().remove(investiture);
                    progressiveClassListOldProgressiveClass = em.merge(progressiveClassListOldProgressiveClass);
                }
            }
            for (ProgressiveClass progressiveClassListNewProgressiveClass : progressiveClassListNew) {
                if (!progressiveClassListOld.contains(progressiveClassListNewProgressiveClass)) {
                    progressiveClassListNewProgressiveClass.getInvestitureList().add(investiture);
                    progressiveClassListNewProgressiveClass = em.merge(progressiveClassListNewProgressiveClass);
                }
            }
            for (Honor honorListOldHonor : honorListOld) {
                if (!honorListNew.contains(honorListOldHonor)) {
                    honorListOldHonor.getInvestitureList().remove(investiture);
                    honorListOldHonor = em.merge(honorListOldHonor);
                }
            }
            for (Honor honorListNewHonor : honorListNew) {
                if (!honorListOld.contains(honorListNewHonor)) {
                    honorListNewHonor.getInvestitureList().add(investiture);
                    honorListNewHonor = em.merge(honorListNewHonor);
                }
            }
            for (Club clubListOldClub : clubListOld) {
                if (!clubListNew.contains(clubListOldClub)) {
                    clubListOldClub.getInvestitureList().remove(investiture);
                    clubListOldClub = em.merge(clubListOldClub);
                }
            }
            for (Club clubListNewClub : clubListNew) {
                if (!clubListOld.contains(clubListNewClub)) {
                    clubListNewClub.getInvestitureList().add(investiture);
                    clubListNewClub = em.merge(clubListNewClub);
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = investiture.getId();
                if (findInvestiture(id) == null) {
                    throw new NonexistentEntityException("The investiture with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            em.getTransaction().begin();
            Investiture investiture;
            try {
                investiture = em.getReference(Investiture.class, id);
                investiture.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The investiture with id " + id + " no longer exists.", enfe);
            }
            Pathfinder pathfinderId = investiture.getPathfinderId();
            if (pathfinderId != null) {
                pathfinderId.getInvestitureList().remove(investiture);
                em.merge(pathfinderId);
            }
            Lider liderId = investiture.getLiderId();
            if (liderId != null) {
                liderId.getInvestitureList().remove(investiture);
                em.merge(liderId);
            }
            List<ProgressiveClass> progressiveClassList = investiture.getProgressiveClassList();
            for (ProgressiveClass progressiveClassListProgressiveClass : progressiveClassList) {
                progressiveClassListProgressiveClass.getInvestitureList().remove(investiture);
                progressiveClassListProgressiveClass = em.merge(progressiveClassListProgressiveClass);
            }
            List<Honor> honorList = investiture.getHonorList();
            for (Honor honorListHonor : honorList) {
                honorListHonor.getInvestitureList().remove(investiture);
                honorListHonor = em.merge(honorListHonor);
            }
            List<Club> clubList = investiture.getClubList();
            for (Club clubListClub : clubList) {
                clubListClub.getInvestitureList().remove(investiture);
                clubListClub = em.merge(clubListClub);
            }
            em.remove(investiture);
            em.getTransaction().commit();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
    }

    @Override
    public List<Investiture> findInvestitureEntities() {
        return findInvestitureEntities(true, -1, -1);
    }

    @Override
    public List<Investiture> findInvestitureEntities(int maxResults, int firstResult) {
        return findInvestitureEntities(false, maxResults, firstResult);
    }

    private List<Investiture> findInvestitureEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Investiture.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public List<Investiture> findCurrentInvestitureEntities() {
        return findCurrentInvestitureEntities(true, -1, -1);
    }

    @Override
    public List<Investiture> findCurrentInvestitureEntities(int maxResults, int firstResult) {
        return findCurrentInvestitureEntities(false, maxResults, firstResult);
    }

    private List<Investiture> findCurrentInvestitureEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Investiture> root = cq.from(Investiture.class);
            cq.select(root);
            cq.where(cb.greaterThanOrEqualTo(root.get(root.getModel().getSingularAttribute("eventDate", Date.class)), cb.currentDate()));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public Investiture findInvestiture(Integer id) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            return em.find(Investiture.class, id);
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public int getInvestitureCount() {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Investiture> rt = cq.from(Investiture.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return 0;
    }

    @Override
    public List<Investiture> findDistinctInvestitureEntities() {
        return findDistinctInvestitureEntities(true, -1, -1);
    }

    @Override
    public List<Investiture> findDistinctInvestitureEntities(int maxResults, int firstResult) {
        return findDistinctInvestitureEntities(false, maxResults, firstResult);
    }
    
    private List<Investiture> findDistinctInvestitureEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Investiture> root = cq.from(Investiture.class);
            cq.multiselect(root.get(InvestitureController.FIELD_PLACE), root.get(InvestitureController.FIELD_EVENT_DATE));
            cq.distinct(true);
            Query q = em.createQuery(cq);
            //TypedQuery<Tuple> q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            List<Object[]> tmpList = q.getResultList();
            List<Investiture> resultList = new ArrayList<>();
            for(Object[] values : tmpList) {
                Investiture tmpInvestiture = new Investiture();
                tmpInvestiture.setPlace((String)values[0]);
                tmpInvestiture.setEventDate((Date)values[1]);
                resultList.add(tmpInvestiture);
            }
            return resultList;
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }

    @Override
    public List<Investiture> findInvestitureEntitiesByPlaceAndDate(String place, Date date) {
        return findInvestitureEntitiesByPlaceAndDate(place, date, true, -1, -1);
    }

    @Override
    public List<Investiture> findInvestitureEntitiesByPlaceAndDate(String place, Date date, int maxResults, int firstResult) {
        return findInvestitureEntitiesByPlaceAndDate(place, date, false, maxResults, firstResult);
    }
    
    private List<Investiture> findInvestitureEntitiesByPlaceAndDate(String place, Date date, boolean all, int maxResults, int firstResult) {
        EntityManager em = null;
        try {
            em = aquireEntityManager();
            CriteriaBuilder cb = em.getCriteriaBuilder();
            CriteriaQuery cq = cb.createQuery();
            Root<Investiture> root = cq.from(Investiture.class);
            cq.select(root);
            cq.where(
                    cb.equal(root.get(root.getModel().getSingularAttribute(FIELD_PLACE, String.class)), place),
                    cb.equal(root.get(root.getModel().getSingularAttribute(FIELD_EVENT_DATE, Date.class)), date)
            );
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } catch(InterruptedException ex) {
        } finally {
            releaseEntityManager(em);
        }
        return null;
    }
}
